﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using EasierRdp.Base;
using EasierRdp.Util;

namespace EasierRdp.Models
{
    class RdpUser : RdpModel
    {
        private readonly IList<RdpServerRef> _servers = new List<RdpServerRef>();
        private readonly IList<RdpSessionRef> _sessions = new List<RdpSessionRef>();
        private readonly IList<RdpSettingRef> _settings = new List<RdpSettingRef>();

        public const string
            ElementName = "User",
            AttributePass = "Pass";

        public string Password { get; set; }

        public bool SavePassword { get; set; }

        public IList<RdpSessionRef> Sessions { get { return _sessions; } }
        public IList<RdpServerRef> Servers { get { return _servers; } }
        public IList<RdpSettingRef> Settings { get { return _settings; } }

        public override IEnumerable<INode> Children
        {
            get { return _servers; }
        }

        public RdpUser(string name)
        {
            Name = name;
        }

        public RdpUser(XElement element)
        {
            if (element != null)
            {
                Name = element.GetString(AttributeName);
                Id = element.GetInt(AttributeId);
                Password = element.GetString(AttributePass);
                Expanded = element.GetBoolean(AttributeExpanded);
                _servers.FromXml(element, RdpServerRef.ElementName);
                SavePassword = !Password.IsNullOrEmpty();
                Password = Password.FromBase64String();
                return;
            }
            throw new ArgumentNullException("element");
        }

        public override XElement ToXml()
        {
            return new XElement(ElementName, 
                        new XAttribute(AttributeExpanded, Expanded),
                        new XAttribute(AttributeId, Id),
                        new XAttribute(AttributeName, Name),
                        SavePassword ? new XAttribute(AttributePass, Password.ToBase64String()) : null,
                        _servers.ToXml()
                    );
        }

        public RdpUser Clone()
        {
            var s = (RdpUser)this.MemberwiseClone();
            s.Id = 0;
            return s;
        }
    }

    static class RdpUserExtension
    {
        public static IEnumerable<XElement> ToXml(this IEnumerable<RdpUser> src)
        {
            return src == null ? null : src.Select(s => s.ToXml());
        }

        public static void FromXml(this IList<RdpUser> src, XElement parentElement, string elementName)
        {
            foreach (var item in parentElement.Elements(elementName).Select(e => new RdpUser(e)))
            {
                src.Add(item);
            }
        }
    }
}
